package day04;

import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * 测输出流的概念
 */
public class Example4 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<String> result = env
                .addSource(new SourceFunction<String>() {
                    @Override
                    public void run(SourceContext<String> ctx) throws Exception {
                        ctx.collectWithTimestamp("atguigu",1000L);
                        Thread.sleep(1000L);
                        ctx.emitWatermark(new Watermark(999L));
                        Thread.sleep(1000L);
                        ctx.collectWithTimestamp("atguigu",500L);
                        Thread.sleep(1000L);
                        ctx.collectWithTimestamp("atguigu",4000L);
                        Thread.sleep(1000L);
                    }

                    @Override
                    public void cancel() {

                    }
                })
                .process(new ProcessFunction<String, String>() {
                    @Override
                    public void processElement(String value, Context ctx, Collector<String> out) throws Exception {
                        if (ctx.timestamp() < ctx.timerService().currentWatermark()){
                            ctx.output(
                                    new OutputTag<String>("late_element"){
                                    },"迟到数据的事件时间是 : " + ctx.timestamp()
                            );
                        }else{
                            out.collect("数据未迟到,他的事件时间是 : " + ctx.timestamp() + ", 此时水位线是 : " + ctx.timerService().currentWatermark());
                        }
                    }
                });
        result.print("主流 : ");
        result.getSideOutput(new OutputTag<String>("late_element"){})
                .print("测流输出 : ");

        env.execute();
    }
}
